package cn.stylefeng.guns.modular.gridsystem.modbus;

import com.serotonin.modbus4j.BasicProcessImage;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusSlaveSet;
import com.serotonin.modbus4j.ProcessImageListener;
import com.serotonin.modbus4j.ip.tcp.TcpSlave;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ModbusTcpProvider {

    @Autowired
    private ModbusTcpConfig modbusTcpConfig;

    @Bean(name = "basicProcessImage")
    private BasicProcessImage createProcessImage() {
        BasicProcessImage processImage = new BasicProcessImage(modbusTcpConfig.getSlaveId());
        processImage.setInvalidAddressValue(Short.MIN_VALUE);
        for (int i = 0; i < 9; i++) {
            processImage.setHoldingRegister(i, Short.valueOf("0"));
        }
        processImage.addListener(new ProcessImageListener() {
            @Override
            public void coilWrite(int offset, boolean oldValue, boolean newValue) {
                log.error("coilWrite: offset:{},oldValue:{},newValue:{}", offset, oldValue, newValue);
            }

            @Override
            public void holdingRegisterWrite(int offset, short oldValue, short newValue) {
                log.error("holdingRegisterWrite: offset:{},oldValue:{},newValue:{}", offset, oldValue, newValue);
            }
        });
        return processImage;
    }

    @Bean("modbusSlaveSet")
    private ModbusSlaveSet createModbusSlaveSet(@Autowired BasicProcessImage basicProcessImage) {
        final ModbusSlaveSet tcpSlave = new TcpSlave(modbusTcpConfig.getPort(),false);
        tcpSlave.addProcessImage(basicProcessImage);
        return tcpSlave;
    }
}
